from appserver import db_store
from sqlalchemy.sql import func
from appserver import db_store
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import func
from sqlalchemy import or_


"""
分区点表
"""

class DistrictItem(db_store.Model):
    __tablename__ = "district_item"
    __bind_key__ = "main"
    # 该表和district相对应
    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    district_id = db_store.Column(db_store.Integer, db_store.ForeignKey('district.id'), nullable=False,
                                     comment=u"分区分类ID")
    lng = db_store.Column(db_store.Float, nullable=False, comment=u'经度')  # 经度
    lat = db_store.Column(db_store.Float, nullable=False, comment=u'纬度')  # 纬度
    dis_order = db_store.Column(db_store.Integer, comment=u"排序，确定绘制顺序", default=0)
    District = relationship("District", backref=backref('district', order_by=id))

    def __repr__(self):
        return "<District %s>" % self.name

    def get_max_id(self):
        val = db_store.session.query(func.max(DistrictItem.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):

        if self.id is None:
            self.id = self.get_max_id() + 1
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print("error is " + e)
            db_store.session.rollback()
            return False

    def delete(self):# delete只做删除功能，其他功能不做
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print(e)
            db_store.session.rollback()
            return False
    
    def get_dic(self):
        rdic={}
        rdic["id"]=self.id
        rdic["district_id"]=self.district_id
        rdic["lng"]=self.lng
        rdic["lat"]=self.lat
        rdic["dis_order"]=self.dis_order
        return rdic

    @staticmethod
    def get_district_item_by_id(id_num):
        return DistrictItem.query.filter_by(id=id_num).first()

    @staticmethod
    def get_district_items_by_district(id_num):
        return DistrictItem.query.filter_by(district_id=id_num).all()

